// server
const datagram = require("dgram");
const searcher = datagram.createSocket("udp4");
const sender = datagram.createSocket("udp4");

const getIpAddress = require("../ip");

const ip = getIpAddress();
const port = Math.round(Math.random() * (19999-15000 + 1) + 15000)
console.log("ip=", ip, 'port',port);

const targetPost = 14099
// const targetPost = 15488

searcher.on('error', e => {
  console.log('error e=', e)
  searcher.close()
  sender.close()
})

searcher.on('message', async msg => {
  const text = msg.toString()
  console.log('message=', text)
})

searcher.bind(port, ip)

sender.bind(0, ip, () => sender.setBroadcast(true))
SocketSend()

function SocketSend() {
  setTimeout(() => {
    sendMsg()
  }, 2);
}

function sendMsg() {
  sender.send(`{"ip": "${ip}", "port": "${port}"}`, targetPost, '255.255.255.255', e => {
    console.log('sender.send e=', e)
    if (e) {
      searcher.close()
      sender.close()
    }

    setTimeout(() => {
      searcher.close()
      sender.close()
      console.log('搜索设备超时了')
    }, 3000);
  })
}